<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary">添加角色</el-button>
      <el-table :data="rolesList" stripe border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              class="verCenter"
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="index === 0 ? 'bd-bottom bd-top' : 'bd-bottom'"
            >
              <!-- 一级权限 -->
              <el-col :span="6">
                <el-tag closable @close="removeRole(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="18">
                <el-row
                  class="verCenter"
                  v-for="(item1, index1) in item.children"
                  :key="item1.id"
                  :class="index1 === 0 ? '' : 'bd-top'"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRole(scope.row, item1.id)"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      type="warning"
                      closable
                      @close="removeRole(scope.row, item2.id)"
                      >{{ item.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small" />
            <el-button type="danger" icon="el-icon-delete" size="small" />
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="success"
                icon="el-icon-s-tools"
                size="small"
                @click="openDialog(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      @close="closeDialog"
    >
      <el-tree
        :data="rightList"
        show-checkbox
        default-expand-all
        :props="defaultProps"
        node-key="id"
        :default-checked-keys="defKeys"
        v-if="treeComVisible"
        ref="tree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      rightList: [],
      dialogVisible: false,
      defaultProps: {
        children: "children",
        label: "authName",
        id: "id",
      },
      //默认选中节点id数组
      defKeys: [],
      treeComVisible: false,
      roleId: 0,
    };
  },
  created() {
    this.getRolesList();
  },
  computed: {},
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      } else {
        this.rolesList = res.data;
      }
    },
    async removeRole(role, rightId) {
      await this.$confirm("此操作将永久删除该角色, 是否继续?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("删除角色失败");
          } else {
            role.children = res.data;
            return this.$message.success("删除角色成功");
          }
        })
        .catch(() => this.$message.info("取消删除"));
    },
    openDialog(role) {
      this.getRightList();
      this.getLeafKeys(role, this.defKeys);
      this.dialogVisible = true;
      this.roleId = role.id;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    //利用递归获取树形结构的所有id值
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      } else {
        node.children.forEach((item) => {
          this.getLeafKeys(item, arr);
        });
      }
    },
    //获取树形结构的权限列表
    async getRightList() {
      const { data: res } = await this.$http.get("rights/tree");
      this.rightList = res.data;
      if (res.meta.status === 200) {
        this.treeComVisible = true;
      } else {
        this.treeComVisible = false;
      }
    },
    closeDialog() {
      this.treeComVisible = false;
      this.defKeys = [];
    },
    async allotRights() {
      let {
        roleId,
        $refs: { tree },
      } = this;
      const ridArr = [...tree.getCheckedKeys(), ...tree.getHalfCheckedKeys()];
      const ridStr = ridArr.join(",");
      const { data: res } = await this.$http.post(`roles/${roleId}/rights`, {
        rids: ridStr,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("分配角色失败");
      }
      this.$message.success("分配角色成功");
      this.getRolesList()
      this.dialogVisible = false
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bd-top {
  border-top: 1px solid #eee;
}
.bd-bottom {
  border-bottom: 1px solid #eee;
}
.el-table {
  margin-top: 7px;
}
</style>